package com.example.app.utils;

import android.os.AsyncTask;
import android.util.Base64;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class XunfeiTranscription {
    private static final String TAG = "XunfeiTranscription";

    // 科大讯飞API相关参数
    private static final String UPLOAD_URL = "https://upload-ost-api.xfyun.cn/file/upload";
    private static final String CREATE_TASK_URL = "https://ost-api.xfyun.cn/v2/ost/pro_create";
    private static final String QUERY_TASK_URL = "https://ost-api.xfyun.cn/v2/ost/query";

    private final String appId;
    private final String apiKey;
    private final String apiSecret;
    private TranscriptionCallback callback;

    public interface TranscriptionCallback {
        void onTranscriptionStart();
        void onTranscriptionProgress(String message);
        void onTranscriptionComplete(String result);
        void onTranscriptionError(String error);
    }

    public XunfeiTranscription(String appId, String apiKey, String apiSecret) {
        // 清理API密钥中的空格和不可见字符
        this.appId = appId.trim();
        this.apiKey = apiKey.trim();
        this.apiSecret = apiSecret.trim();
        
        // 验证API密钥格式
        if (this.apiKey.isEmpty() || this.apiSecret.isEmpty()) {
            Log.e(TAG, "API密钥不能为空");
        }
        
        // 记录清理后的密钥长度，用于调试
        Log.d(TAG, String.format("API密钥长度 - AppId: %d, ApiKey: %d, ApiSecret: %d", 
            this.appId.length(), this.apiKey.length(), this.apiSecret.length()));
    }

    public void setCallback(TranscriptionCallback callback) {
        this.callback = callback;
    }

    public void startTranscription(File audioFile) {
        new TranscriptionTask().execute(audioFile);
    }

    public void startTranscriptionWithData(byte[] audioData) {
        new TranscriptionTask().execute(audioData);
    }

    private class TranscriptionTask extends AsyncTask<Object, String, String> {
        public void updateProgress(String progress) {
            publishProgress(progress);
        }

        @Override
        protected void onPreExecute() {
            if (callback != null) {
                callback.onTranscriptionStart();
            }
        }

        @Override
        protected String doInBackground(Object... params) {
            String result = "";
            try {
                if (params[0] instanceof File) {
                    File audioFile = (File) params[0];
                    updateProgress("正在上传音频文件...");
                    String audioUrl = uploadAudioFile(audioFile);

                    if (audioUrl != null) {
                        updateProgress("正在创建转写任务...");
                        String taskId = createTranscriptionTask(audioUrl, this);

                        if (taskId != null && !taskId.startsWith("转写失败") && !taskId.startsWith("创建转写任务错误")) {
                            updateProgress("正在进行转写，请稍候...");
                            result = queryTranscriptionResult(taskId, this);
                        } else {
                            result = taskId;
                        }
                    } else {
                        result = "上传音频文件失败";
                    }
                } else if (params[0] instanceof byte[]) {
                    byte[] audioData = (byte[]) params[0];
                    updateProgress("正在上传音频文件...");
                    String audioUrl = uploadAudioData(audioData);

                    if (audioUrl != null) {
                        updateProgress("正在创建转写任务...");
                        String taskId = createTranscriptionTask(audioUrl, this);

                        if (taskId != null && !taskId.startsWith("转写失败") && !taskId.startsWith("创建转写任务错误")) {
                            updateProgress("正在进行转写，请稍候...");
                            result = queryTranscriptionResult(taskId, this);
                        } else {
                            result = taskId;
                        }
                    } else {
                        result = "上传音频文件失败";
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "转写过程出错", e);
                result = "转写过程出错: " + e.getMessage();
            }
            return result;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            if (callback != null) {
                callback.onTranscriptionProgress(values[0]);
            }
        }

        @Override
        protected void onPostExecute(String result) {
            if (callback != null) {
                if (result != null && !result.isEmpty() &&
                        !result.startsWith("错误") &&
                        !result.startsWith("转写失败") &&
                        !result.startsWith("查询转写结果HTTP错误") &&
                        !result.startsWith("未检测到有效语音")) {
                    callback.onTranscriptionComplete(result);
                } else {
                    callback.onTranscriptionError(result);
                }
            }
        }
    }

    private String uploadAudioFile(File audioFile) throws IOException, NoSuchAlgorithmException, InvalidKeyException, JSONException {
        String requestId = UUID.randomUUID().toString().replace("-", "");
        String date = getGMTDate();
        String boundary = UUID.randomUUID().toString().replace("-", "");
        URL url = new URL(UPLOAD_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        conn.setRequestProperty("Host", url.getHost());
        conn.setRequestProperty("Date", date);

        StringBuilder bodyBuilder = new StringBuilder();
        bodyBuilder.append("--").append(boundary).append("\r\n");
        bodyBuilder.append("Content-Disposition: form-data; name=\"app_id\"\r\n\r\n");
        bodyBuilder.append(appId).append("\r\n");
        bodyBuilder.append("--").append(boundary).append("\r\n");
        bodyBuilder.append("Content-Disposition: form-data; name=\"request_id\"\r\n\r\n");
        bodyBuilder.append(requestId).append("\r\n");

        String bodyPrefix = bodyBuilder.toString();
        String bodySuffix = "\r\n--" + boundary + "--\r\n";

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(bodyPrefix.getBytes(StandardCharsets.UTF_8));

        String fileHeader = "--" + boundary + "\r\n" +
                "Content-Disposition: form-data; name=\"data\";filename=\"" + audioFile.getName() + "\"\r\n" +
                "Content-Type: audio/pcm\r\n\r\n";
        md.update(fileHeader.getBytes(StandardCharsets.UTF_8));

        FileInputStream fis = new FileInputStream(audioFile);
        byte[] buffer = new byte[8192];
        int bytesRead;
        while ((bytesRead = fis.read(buffer)) != -1) {
            md.update(buffer, 0, bytesRead);
        }
        fis.close();

        md.update(bodySuffix.getBytes(StandardCharsets.UTF_8));
        String digest = "SHA-256=" + Base64.encodeToString(md.digest(), Base64.NO_WRAP);

        String requestLine = "POST " + new URL(UPLOAD_URL).getPath() + " HTTP/1.1";
        String signatureOrigin = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                requestLine + "\n" +
                "digest: " + digest;

        String signature = calculateSignature(signatureOrigin, apiSecret);
        String authorization = "api_key=\"" + apiKey + "\", algorithm=\"hmac-sha256\", " +
                "headers=\"host date request-line digest\", signature=\"" + signature + "\"";

        conn.setRequestProperty("Authorization", authorization);
        conn.setRequestProperty("Digest", digest);

        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.writeBytes(bodyPrefix);
        out.writeBytes("--" + boundary + "\r\n");
        out.writeBytes("Content-Disposition: form-data; name=\"data\";filename=\"" + audioFile.getName() + "\"\r\n");
        out.writeBytes("Content-Type: audio/pcm\r\n\r\n");

        fis = new FileInputStream(audioFile);
        while ((bytesRead = fis.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
        }
        fis.close();

        out.writeBytes("\r\n--" + boundary + "--\r\n");
        out.flush();
        out.close();

        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            JSONObject jsonResponse = new JSONObject(response.toString());
            if (jsonResponse.getInt("code") == 0) {
                return jsonResponse.getJSONObject("data").getString("url");
            } else {
                Log.e(TAG, "上传音频文件响应错误: " + jsonResponse.toString());
                return null;
            }
        } else {
            Log.e(TAG, "上传音频文件HTTP错误: " + responseCode);
            return null;
        }
    }

    private String createTranscriptionTask(String audioUrl, TranscriptionTask task) throws IOException, NoSuchAlgorithmException, InvalidKeyException, JSONException {
        JSONObject postData = new JSONObject();
        postData.put("common", new JSONObject().put("app_id", appId));
        String requestId = UUID.randomUUID().toString().replace("-", "");
        postData.put("business", new JSONObject()
                .put("request_id", requestId)
                .put("language", "zh_cn")
                .put("domain", "pro_ost_ed")
                .put("accent", "mandarin"));
        postData.put("data", new JSONObject()
                .put("audio_url", audioUrl)
                .put("audio_src", "http")
                .put("format", "audio/L16;rate=16000")
                .put("encoding", "raw"));

        URL url = new URL(CREATE_TASK_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        String date = getGMTDate();
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Host", "ost-api.xfyun.cn");
        conn.setRequestProperty("Date", date);

        String signature = calculateSignature("POST", "application/json", "/v2/ost/pro_create", date, apiKey, apiSecret);
        conn.setRequestProperty("Authorization", signature);

        try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
            wr.write(postData.toString().getBytes(StandardCharsets.UTF_8));
            wr.flush();
        }

        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder response = new StringBuilder();
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            JSONObject jsonResponse = new JSONObject(response.toString());
            if (jsonResponse.getInt("code") == 0) {
                return jsonResponse.getJSONObject("data").getString("task_id");
            } else {
                return "创建转写任务错误: " + jsonResponse.getString("message");
            }
        } else {
            StringBuilder errorResponse = new StringBuilder();
            try {
                BufferedReader errorReader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
                String errorLine;
                while ((errorLine = errorReader.readLine()) != null) {
                    errorResponse.append(errorLine);
                }
                errorReader.close();
                
                try {
                    JSONObject errorJson = new JSONObject(errorResponse.toString());
                    String errorMessage = errorJson.optString("message", "");
                    
                    if (responseCode == 401) {
                        if (errorMessage.contains("HMAC signature does not match")) {
                            return "认证失败：API密钥可能不正确，请检查AppID、APIKey和APISecret是否正确设置，并确保没有多余的空格";
                        } else {
                            return "认证失败：请检查API密钥配置是否正确";
                        }
                    } else {
                        return "创建转写任务失败：" + errorMessage;
                    }
                } catch (JSONException e) {
                    if (responseCode == 401) {
                        return "认证失败：请检查API密钥配置是否正确";
                    }
                    return "创建转写任务失败：HTTP错误 " + responseCode;
                }
            } catch (Exception e) {
                if (responseCode == 401) {
                    return "认证失败：请检查API密钥配置是否正确";
                }
                return "创建转写任务失败：HTTP错误 " + responseCode;
            }
        }
    }

    private String queryTranscriptionResult(String taskId, TranscriptionTask task) throws IOException, NoSuchAlgorithmException, InvalidKeyException, JSONException, InterruptedException {
        JSONObject postData = new JSONObject();
        postData.put("common", new JSONObject().put("app_id", appId));
        postData.put("business", new JSONObject().put("task_id", taskId));

        int[] waitTimes = {1, 1, 2, 2, 3, 3, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5};
        int totalWaitedTime = 0;

        for (int i = 0; i < waitTimes.length; i++) {
            URL url = new URL(QUERY_TASK_URL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);

            String date = getGMTDate();
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Host", "ost-api.xfyun.cn");
            conn.setRequestProperty("Date", date);

            String signature = calculateSignature("POST", "application/json", "/v2/ost/query", date, apiKey, apiSecret);
            conn.setRequestProperty("Authorization", signature);

            try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
                wr.write(postData.toString().getBytes(StandardCharsets.UTF_8));
                wr.flush();
            }

            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder response = new StringBuilder();
                String inputLine;

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                JSONObject jsonResponse = new JSONObject(response.toString());
                if (jsonResponse.getInt("code") == 0) {
                    JSONObject data = jsonResponse.getJSONObject("data");
                    String taskStatus = data.getString("task_status");

                    if (taskStatus.equals("4")) {
                        if (data.has("result")) {
                            StringBuilder resultText = new StringBuilder();
                            JSONArray lattice = data.getJSONObject("result").getJSONArray("lattice");

                            for (int j = 0; j < lattice.length(); j++) {
                                JSONObject latticeItem = lattice.getJSONObject(j);
                                JSONObject json1best = latticeItem.getJSONObject("json_1best");
                                JSONObject st = json1best.getJSONObject("st");
                                JSONArray rt = st.getJSONArray("rt");

                                for (int k = 0; k < rt.length(); k++) {
                                    JSONArray ws = rt.getJSONObject(k).getJSONArray("ws");

                                    for (int l = 0; l < ws.length(); l++) {
                                        JSONArray cw = ws.getJSONObject(l).getJSONArray("cw");
                                        for (int m = 0; m < cw.length(); m++) {
                                            JSONObject cwItem = cw.getJSONObject(m);
                                            String word = cwItem.getString("w");
                                            if (!word.isEmpty() && !word.equals("。") && !word.equals("，") && !word.equals("？") && !word.equals("！")) {
                                                resultText.append(word);
                                            }
                                        }
                                    }
                                }
                            }

                            return resultText.toString();
                        } else {
                            return "转写结果为空，可能没有检测到语音";
                        }
                    } else if (taskStatus.equals("1") || taskStatus.equals("2")) {
                        totalWaitedTime += waitTimes[i];
                        task.updateProgress("任务排队中，已等待" + totalWaitedTime + "秒...");
                        TimeUnit.SECONDS.sleep(waitTimes[i]);
                        continue;
                    } else {
                        return "转写任务异常: 未知状态 " + taskStatus;
                    }
                } else {
                    return "查询转写结果错误: " + jsonResponse.optString("message", "未知错误");
                }
            } else {
                StringBuilder errorResponse = new StringBuilder();
                try {
                    BufferedReader errorReader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
                    String errorLine;
                    while ((errorLine = errorReader.readLine()) != null) {
                        errorResponse.append(errorLine);
                    }
                    errorReader.close();

                    try {
                        JSONObject errorJson = new JSONObject(errorResponse.toString());
                        String errorMessage = errorJson.optString("message", "");
                        
                        if (responseCode == 401) {
                            if (errorMessage.contains("HMAC signature does not match")) {
                                return "认证失败：API密钥可能不正确，请检查AppID、APIKey和APISecret是否正确设置，并确保没有多余的空格";
                            } else {
                                return "认证失败：请检查API密钥配置是否正确";
                            }
                        } else if (errorJson.has("data") && errorJson.getJSONObject("data").has("task_status")
                                && "4".equals(errorJson.getJSONObject("data").getString("task_status"))) {
                            return "未检测到有效语音内容，请重试";
                        } else {
                            return "查询转写结果失败：" + errorMessage;
                        }
                    } catch (JSONException e) {
                        if (responseCode == 401) {
                            return "认证失败：请检查API密钥配置是否正确";
                        }
                        return "查询转写结果失败：HTTP错误 " + responseCode;
                    }
                } catch (Exception e) {
                    Log.e(TAG, "读取错误响应失败", e);
                    if (responseCode == 401) {
                        return "认证失败：请检查API密钥配置是否正确";
                    }
                    return "查询转写结果失败：HTTP错误 " + responseCode;
                }
            }
        }

        return "转写超时，请稍后再试";
    }

    private String uploadAudioData(byte[] audioData) throws IOException, NoSuchAlgorithmException, InvalidKeyException, JSONException {
        String requestId = UUID.randomUUID().toString().replace("-", "");
        String date = getGMTDate();
        String boundary = UUID.randomUUID().toString().replace("-", "");
        URL url = new URL(UPLOAD_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        Log.d(TAG, "开始上传音频数据，数据大小: " + audioData.length + " 字节");

        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        conn.setRequestProperty("Host", url.getHost());
        conn.setRequestProperty("Date", date);

        StringBuilder bodyBuilder = new StringBuilder();
        bodyBuilder.append("--").append(boundary).append("\r\n");
        bodyBuilder.append("Content-Disposition: form-data; name=\"app_id\"\r\n\r\n");
        bodyBuilder.append(appId).append("\r\n");
        bodyBuilder.append("--").append(boundary).append("\r\n");
        bodyBuilder.append("Content-Disposition: form-data; name=\"request_id\"\r\n\r\n");
        bodyBuilder.append(requestId).append("\r\n");

        String bodyPrefix = bodyBuilder.toString();
        String bodySuffix = "\r\n--" + boundary + "--\r\n";

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(bodyPrefix.getBytes(StandardCharsets.UTF_8));

        String fileName = "audio_" + System.currentTimeMillis() + ".pcm";
        String fileHeader = "--" + boundary + "\r\n" +
                "Content-Disposition: form-data; name=\"data\";filename=\"" + fileName + "\"\r\n" +
                "Content-Type: audio/pcm\r\n\r\n";
        md.update(fileHeader.getBytes(StandardCharsets.UTF_8));
        md.update(audioData);
        md.update(bodySuffix.getBytes(StandardCharsets.UTF_8));

        String digest = "SHA-256=" + Base64.encodeToString(md.digest(), Base64.NO_WRAP);
        String requestLine = "POST " + url.getPath() + " HTTP/1.1";
        
        // 修改签名生成方式
        String signatureOrigin = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                requestLine + "\n" +
                "digest: " + digest;

        Log.d(TAG, "签名原文: " + signatureOrigin);

        String signature = calculateSignature(signatureOrigin, apiSecret);
        String authorization = "api_key=\"" + apiKey + "\", algorithm=\"hmac-sha256\", " +
                "headers=\"host date request-line digest\", signature=\"" + signature + "\"";

        Log.d(TAG, "Authorization: " + authorization);
        Log.d(TAG, "Digest: " + digest);

        conn.setRequestProperty("Authorization", authorization);
        conn.setRequestProperty("Digest", digest);

        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.writeBytes(bodyPrefix);
        out.writeBytes("--" + boundary + "\r\n");
        out.writeBytes("Content-Disposition: form-data; name=\"data\";filename=\"" + fileName + "\"\r\n");
        out.writeBytes("Content-Type: audio/pcm\r\n\r\n");
        out.write(audioData);
        out.writeBytes("\r\n--" + boundary + "--\r\n");
        out.flush();
        out.close();

        Log.d(TAG, "音频数据已写入输出流");

        int responseCode = conn.getResponseCode();
        Log.d(TAG, "上传响应码: " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            Log.d(TAG, "上传响应内容: " + response.toString());

            JSONObject jsonResponse = new JSONObject(response.toString());
            if (jsonResponse.getInt("code") == 0) {
                String audioUrl = jsonResponse.getJSONObject("data").getString("url");
                Log.d(TAG, "获取到音频URL: " + audioUrl);
                return audioUrl;
            } else {
                Log.e(TAG, "上传音频文件响应错误: " + jsonResponse.toString());
                return null;
            }
        } else {
            // 读取错误响应
            StringBuilder errorResponse = new StringBuilder();
            try {
                BufferedReader errorReader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
                String errorLine;
                while ((errorLine = errorReader.readLine()) != null) {
                    errorResponse.append(errorLine);
                }
                errorReader.close();
                Log.e(TAG, "上传失败，错误响应: " + errorResponse.toString());
                
                // 解析错误响应
                try {
                    JSONObject errorJson = new JSONObject(errorResponse.toString());
                    String errorMessage = errorJson.optString("message", "");
                    
                    if (responseCode == 401) {
                        if (errorMessage.contains("HMAC signature does not match")) {
                            return "认证失败：API密钥可能不正确，请检查AppID、APIKey和APISecret是否正确设置，并确保没有多余的空格";
                        } else {
                            return "认证失败：请检查API密钥配置是否正确";
                        }
                    } else {
                        return "上传失败：" + errorMessage;
                    }
                } catch (JSONException e) {
                    if (responseCode == 401) {
                        return "认证失败：请检查API密钥配置是否正确";
                    }
                    return "上传失败：HTTP错误 " + responseCode;
                }
            } catch (Exception e) {
                Log.e(TAG, "读取错误响应失败", e);
                if (responseCode == 401) {
                    return "认证失败：请检查API密钥配置是否正确";
                }
                return "上传失败：HTTP错误 " + responseCode;
            }
        }
    }

    private String getGMTDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        return sdf.format(new Date());
    }

    private String calculateSignature(String data, String key) throws NoSuchAlgorithmException, InvalidKeyException {
        Mac sha256HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        sha256HMAC.init(secretKey);
        byte[] hash = sha256HMAC.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.encodeToString(hash, Base64.NO_WRAP);
    }

    private String calculateSignature(String method, String contentType, String path, String date, String apiKey, String apiSecret) throws NoSuchAlgorithmException, InvalidKeyException {
        String signatureOrigin = "host: ost-api.xfyun.cn\n" +
                "date: " + date + "\n" +
                method + " " + path + " HTTP/1.1\n" +
                "content-type: " + contentType;

        Mac sha256HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKey = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        sha256HMAC.init(secretKey);
        String signature = Base64.encodeToString(sha256HMAC.doFinal(signatureOrigin.getBytes(StandardCharsets.UTF_8)), Base64.NO_WRAP);

        return "api_key=\"" + apiKey + "\", algorithm=\"hmac-sha256\", " +
                "headers=\"host date request-line content-type\", signature=\"" + signature + "\"";
    }
} 